package cn.hfatec.shms.system.authData.action;

import cn.hfatec.JsonResponse;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.constants.SysContant;
import cn.hfatec.freemarker.FreeMarkerUtil;
import cn.hfatec.shms.base.ShmsBaseAction;
import cn.hfatec.shms.system.authData.model.AuthData;
import cn.hfatec.shms.system.authData.model.AuthDataParams;
import cn.hfatec.shms.system.authData.service.AuthDataService;
import cn.hfatec.shms.system.authResource.service.AuthResourceService;
import cn.hfatec.shms.system.resource.model.ResourceParams;
import cn.hfatec.shms.system.resource.model.Resources;
import cn.hfatec.shms.system.resource.service.ResourceService;
import com.google.common.base.Optional;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;



/**
 *
 * @author hfatec codegen
 * @version 1.0
 *
 * the JAVA code is generate by middlegen
 *
 */
@Controller
@RequestMapping("/system/authData")
public class AuthDataAction extends ShmsBaseAction {

    //服务层
    @Resource(name = "AuthDataService")
    private AuthDataService authDataService;

    @Resource(name = "AuthResourceService")
    private AuthResourceService authResourceService;

    @Resource(name = "ResourceService")
    private ResourceService resourceService;


    /**
     *
     * 查询列表
     *
     */
    @RequestMapping("/list")
    public String list(AuthDataParams authDataParams, Page page, Model model) {

        Table table = authDataService.queryAuthDataTable(authDataParams, page);
        model.addAttribute("authDatasTable", table);
        model.addAttribute("authDataParams", authDataParams);
        return "/system/authData/list";
    }

    /**
     *
     * 异步查询列表
     *
     */
    @RequestMapping("/ajaxList")
    @ResponseBody
    public String ajaxList(AuthDataParams authDataParams, Page page, Model model) {
        try {
            list(authDataParams, page, model);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/authData/table", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     *
     * 异步查询列表
     *
     */
    @RequestMapping("/ajaxListByModuleId")
    @ResponseBody
    public String ajaxListByModuleId(AuthDataParams authDataParams,Model model) {
        try {
            List list = authDataService.queryAuthDataList(authDataParams);
            model.addAttribute("authDatasList",list);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/module/moduleAuthTable", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     *
     * 跳转到新增页
     *
     */
    @RequestMapping("/goAdd")
    @ResponseBody
    public String goAdd(String moduleId, Model model) {
        try {
            AuthData authData = new AuthData();
            model.addAttribute("moduleId", moduleId);
            model.addAttribute("authData", authData);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/authData/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     *
     * 跳转到编辑页
     *
     */
    @RequestMapping("/goEdit")
    @ResponseBody
    public String goEdit(Integer id, Model model) {

        try {
            AuthData authData = authDataService.getAuthData(id);
            model.addAttribute("authData", authData);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/authData/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     *
     * 根据IDs删除数据
     *
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String deleteAuthData(String ids, String moduleId) {
        try {
            List<String> idList = new ArrayList<String>();
            if(ids.length() > 0) {
                idList = Arrays.asList(ids.split(","));
            }
            authDataService.deleteAuthDataBatch(idList, moduleId);
        } catch(Exception e) {
            e.printStackTrace();
            logger.error("数据" + ids + "删除异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.DELETE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse(JsonResponse.RETURN_SUCCESS, SysContant.DELETE_SUCCESS_MESSAGE).toString();
    }

    /**
     *
     * 保存数据
     *
     */
    @RequestMapping("/save")
    @ResponseBody
    public String saveAuthData(@Valid AuthData authData,String moduleId, BindingResult result) {

        try {
            if(result.hasErrors()) {
                List<ObjectError> errors = result.getAllErrors();
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, errors.get(0).getDefaultMessage()).toString();
            }
            if (authData.getId() == null) {
                Optional<JsonResponse<String>> optional = authDataService.checkAuthIdRepeat(authData);
                if (optional.isPresent()) {
                    return optional.get().toString();
                }
            }
            authDataService.saveAuthData(authData,moduleId);
        } catch(Exception e) {
            e.printStackTrace();
            logger.error("数据AuthData保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, SysContant.SAVE_SUCCESS_MESSAGE).toString();
    }

    /**
     *
     * 跳转到资源分配界面
     *
     * @return
     */
    @RequestMapping("/goAssign")
    @ResponseBody
    public String goAssignResource(@RequestParam("authId") String authId,@RequestParam("moduleId") String moduleId, Page page, Model model) {
        try {

            List assignResourceList = authResourceService.queryAssignResourceList(authId);
            ResourceParams resourceParams = new ResourceParams();
            resourceParams.setModuleId(moduleId);
            resourceParams.setAuthId(authId);
            Table<Resources> resourceList = resourceService.queryResourceTable(resourceParams, page);

            model.addAttribute("resourcesTable", resourceList);
            model.addAttribute("assignResourceList", assignResourceList);
            model.addAttribute("authId", authId);
            model.addAttribute("moduleId", moduleId);

            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/authData/assignResource", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     *
     * 资源分配异步查询
     *
     * @return
     */
    @RequestMapping("/ajaxAssignResourceList")
    @ResponseBody
    public String ajaxAssignResourceList(@RequestParam("authId") String authId,@RequestParam("moduleId") String moduleId, Page page, Model model) {
        try {

            List assignResourceList = authResourceService.queryAssignResourceList(authId);
            ResourceParams resourceParams = new ResourceParams();
            resourceParams.setModuleId(moduleId);
            resourceParams.setAuthId(authId);
            Table<Resources> resourceList = resourceService.queryResourceTable(resourceParams, page);

            model.addAttribute("resourcesTable", resourceList);
            model.addAttribute("assignResourceList", assignResourceList);
            model.addAttribute("authId", authId);
            model.addAttribute("moduleId", moduleId);

            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/authData/assignResourceTable", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }
//



    /**
     *
     * 分配权限、资源关系
     *
     * @param authId
     * @param ids
     * @param allIds
     * @return
     */
    @RequestMapping("/assign")
    @ResponseBody
    public String assignResources(String authId, @RequestParam(value = "resourceIds", required = false)String[] ids, String[] allIds) {

        try {

            authResourceService.assignResources(authId, ids, allIds);
        } catch(Exception e) {
            e.printStackTrace();
            logger.error("数据AuthData保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, SysContant.SAVE_SUCCESS_MESSAGE).toString();
    }
}
